package com.uestc.admin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import com.qiniu.storage.model.FileInfo;
import com.uestc.qiniu.QNManager;
import com.uestc.servlet.admin.config.ReadConfig;
import com.uestc.util.JsonUtil;

public class QiniuAdmin implements AdminBase {

	private final static String COLUMN_NAME = "QiniuColumns";

	@Override
	public String getInfo(int page, int limit, HttpServletRequest request) throws Throwable {
		String marker = null;
		long totalProperty = 0;
		if (page > 0) {
			marker = (String) request.getSession().getAttribute("marker");
			totalProperty = (long) request.getSession().getAttribute("totalProperty") + limit;
		} else
			totalProperty = limit * 2;
		request.getSession().setAttribute("totalProperty", totalProperty);

		String[] columns = ReadConfig.getItems("QiniuColumns");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("success", "true");
		map.put("totalProperty", totalProperty);
		ArrayList<Object> jsonArray = new ArrayList<>();
		QNManager qnManager = new QNManager();

		FileInfo[] fileInfos = qnManager.getFilesInfo(limit, marker);
		for (FileInfo fileinfo : fileInfos) {
			HashMap<String, Object> tempMap = new HashMap<>();
			for (String column : columns) {
				String columnName = JsonUtil.getAttribute(column, "columnName");
				String fileInfo = JsonUtil.getAttribute(column, "fileInfo");
				tempMap.put(columnName, fileinfo.getClass().getField(fileInfo).get(fileinfo));
			}
			jsonArray.add(tempMap);
		}
		map.put("rows", jsonArray);
		request.getSession().setAttribute("marker", qnManager.getMarker());
		String result = JsonUtil.createJsonString(map);
		System.out.print(result);
		return result;
	}

	public static String toLocalTime(String unix) {
		Long timestamp = Long.parseLong(unix) * 1000;
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(timestamp));
		return date;
	}

	@Override
	public String getColumnName() {
		return COLUMN_NAME;
	}

	@Override
	public String getInfoWithCondition(int page, int limit, HashMap<String, String> conditions,
			HttpServletRequest request) throws Throwable {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getTableName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getDateColumnName() {
		// TODO Auto-generated method stub
		return null;
	}

}
